package repository

import (
	"github.com/google/uuid"
	"gorm.io/gorm"

	"bbs/pkg/domain"
)

type userRepository struct {
	DB *gorm.DB
}

func NewUserRepository(db *gorm.DB) domain.UserRepository {
	return &userRepository{
		DB: db,
	}
}

func (repo *userRepository) CreateUser(user *domain.User) error {
	// create uuid for User
	user.ID = uuid.New().String()

	return repo.DB.Create(user).Error
}

func (repo *userRepository) UpdateUser(user *domain.User) error {
	return repo.DB.Save(user).Error
}

func (repo *userRepository) GetUserByID(userID string) (*domain.User, error) {
	u := &domain.User{}
	err := repo.DB.First(u, "id = ?", userID).Error
	return u, err
}

func (repo *userRepository) GetUserByName(name string) (*domain.User, error) {
	u := domain.User{}
	err := repo.DB.Where("name = ?", name).First(&u).Error
	return &u, err
}

func (repo *userRepository) GetUserByEmail(email string) (*domain.User, error) {
	u := domain.User{}
	err := repo.DB.Where("email = ?", email).First(&u).Error
	return &u, err
}
